package com.bizihang.controller.async;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author 毕子航 951755883@qq.com
 * @date 2018/08/15
 */
@Slf4j
@Component
public class QueueListener implements ApplicationListener<ContextRefreshedEvent> {
	@Autowired
	MockQueue mockQueue;
	@Autowired
	DeferredResultHolder deferredResultHolder;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		new Thread(() -> {
			//应用1：监听消息队列中订单的处理结果
			while (true) {
				if (StringUtils.hasText(mockQueue.getCompleteOrder())) {
					//线程2：模拟线程2获取返回结果
					String orderNumber = mockQueue.getCompleteOrder();
					log.info("返回订单处理结果:{}", orderNumber);
					deferredResultHolder.getMap().get(orderNumber).setResult("place order success"+orderNumber);
					mockQueue.setCompleteOrder(null);
				} else {
					try {
						Thread.sleep(100L);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}
}
